﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Build.Framework;
using ZealandIT.MsBuildTasks.Common;

namespace ZealandIT.MsBuildTasks.IO
{
    /// <summary>
    /// MSBuild task that copies directory(ies) recursively and uses impersonation - if 
    /// username/pw specified.
    /// This allows the operation to work over UNC / network paths.
    /// </summary>
    public class CpDir : BaseImpersonationTask
    {
        private string _from;
        private string _to;

        /// <summary>
        /// Source directory.
        /// </summary>
        [Required]
        public string From
        {
            get { return _from; }
            set { _from = value; }
        }

        /// <summary>
        /// Target directory.
        /// </summary>
        [Required]
        public string To
        {
            get { return _to; }
            set { _to = value; }
        }

        /// <summary>
        /// Main work takes place here - this method is called from its
        /// abstract base class' <see cref="BaseImpersonationTask.Execute"/> method.
        /// </summary>
        /// <returns>True if successful, else false.</returns>
        protected override bool ExecuteInternal()
        {
            try
            {
                Log.LogMessage(string.Format("Copying directory \"{0}\" to \"{1}\"...", _from,_to));
                IoHelper.CopyDirectoryRecursively(_from,_to);
                Log.LogMessage("..done.");
            }
            catch (Exception ex)
            {
                Log.LogMessage("..FAILED.");
                Log.LogErrorFromException(ex);
                return false;
            }
            return true;
        }
    }
}
